// stores/usePictureStore.ts
import { defineStore } from 'pinia'
import { listPictureVoByPageUsingPost } from '@/api/pictureController'

export const usePictureStore = defineStore('picture', {
  state: () => ({
    // 使用Map存储实时数据
    viewCounts: new Map<number, number>(),
    likeCounts: new Map<number, number>(),
    likeStatus: new Map<number, boolean>()
  }),
  actions: {
    // 更新单个图片状态
    updatePictureStats(pictureId: number, stats: {
      viewCount?: number
      likeCount?: number
      isLiked?: boolean
    }) {
      if (stats.viewCount !== undefined) {
        this.viewCounts.set(pictureId, stats.viewCount)
      }
      if (stats.likeCount !== undefined) {
        this.likeCounts.set(pictureId, stats.likeCount)
      }
      if (stats.isLiked !== undefined) {
        this.likeStatus.set(pictureId, stats.isLiked)
      }
    },

    // 定时同步最新数据
    async syncLatestData() {
      try {
        const res = await listPictureVoByPageUsingPost({
          pageSize: 1000 // 根据实际情况调整
        })
        res.data.data?.records?.forEach(pic => {
          this.updatePictureStats(pic.id!, {
            viewCount: pic.viewCount || 0,
            likeCount: pic.likeCount || 0
          })
        })
      } catch (e) {
        console.error('同步数据失败', e)
      }
    }
  }
})
